package com.huobi.db.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.stream.IntStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.huobi.db.bean.HbTradeDetail;
import com.huobi.db.mapper.TradeDetailMapper;
import com.huobi.event.TradeDataEvent;

@Service
public class HbTradeDataService {

	@Autowired TradeDetailMapper tradeDetailMapper;
	@Autowired PartitionService partitionService;

	private final BlockingQueue<HbTradeDetail> queue = new LinkedBlockingDeque<>(10000);
	
	@EventListener
	public void onApplicationEvent(TradeDataEvent event) { 
		final HbTradeDetail[] arrays = event.getData();
		IntStream.range(0,arrays.length).forEach(i -> {
			queue.offer(arrays[i]);
		});
	}

	@Scheduled(cron = "0/1 * * * * ?")
	public void batchSave() throws InterruptedException {
		partitionService.partition(tradeDetailMapper);
		List<HbTradeDetail> list = new ArrayList<>();
		queue.drainTo(list);
		if (list.isEmpty())
			return;
		tradeDetailMapper.batchInsert(partitionService.getCurrentDaily(), list);
	}

}
